﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using CNKI.TPI.Web.Base;
using CNKI.TPI.Web.UI.Filters;
using System.Web.Security;
using CNKI.TPI.Web.UI.Models;
using Castle.DynamicProxy;
using CNKI.TPI.Web.Search.IBLL;
using CNKI.TPI.Web.Search.Model;
using System.Web.SessionState;
using System.Collections;
using System.Runtime.Serialization.Formatters.Binary;
using System.Runtime.Serialization.Formatters.Soap;
using CNKI.TPI.Web.Admin.IBLL;
using CNKI.TPI.Web.Admin.Model;

namespace CNKI.TPI.Web.UI.Controllers.Search
{
    [SessionState(SessionStateBehavior.ReadOnly)]
    public class TopicMultiSearchController : BaseController
    {
        //
        // GET: /MultiSearch/
        IUserService userService = null;
        ISearchService searchService = null;
        IUserCenterService centerService = null;
        private ITopicService topicService = null;

        public TopicMultiSearchController(ITopicService subjectService, IUserService userService, ISearchService searchService, IUserCenterService centerService)
        {
            this.topicService = generator.CreateInterfaceProxyWithTarget<ITopicService>(subjectService, new IInterceptor[] { new LogInterceptor() });
            this.userService = generator.CreateInterfaceProxyWithTarget<IUserService>(userService, new IInterceptor[] { new LogInterceptor() });
            this.searchService = generator.CreateInterfaceProxyWithTarget<ISearchService>(searchService, new IInterceptor[] { new LogInterceptor() });
            this.centerService = generator.CreateInterfaceProxyWithTarget<IUserCenterService>(centerService, new IInterceptor[] { new LogInterceptor() });
        }

        [ValidateInput(false)]
        [SecurityActionFilter]
        public ActionResult Index()
        {
            //相似词搜索网址
            //ViewBag.smartWordAddress = ConfigHelper.GetAppSettingsValue("smartWordAddress");
            string searchField = "";
            string conditionKey = "";
            string checkDatabaseID = "";
            string unionDBClassID = "";
            int searchLog = -1;
            string topicCode = "";
            ConditionType conditionType = ConditionType.Like;
            if (!String.IsNullOrEmpty(Request.Params["searchField"]))
            {
                searchField = Request.Params["searchField"];//查询值
            }
            if (!String.IsNullOrEmpty(Request.Params["conditionKey"]))
            {
                conditionKey = Request.Params["conditionKey"];// 查询字段
            }
            if (!String.IsNullOrEmpty(Request.Params["checkDatabaseID"]))
            {
                checkDatabaseID = Request.Params["checkDatabaseID"];
            }
            if (!String.IsNullOrEmpty(Request.Params["currentClassID"]))
            {
                unionDBClassID = Request.Params["currentClassID"];
            }
            if (!String.IsNullOrEmpty(Request.Params["TopicCode"]))
            {
                topicCode = Request.Params["TopicCode"];
            }
            if (!String.IsNullOrEmpty(Request.Params["searchLog"]))
            {
                searchLog = int.Parse(Request.Params["searchLog"]);
            }
            if (Request.Cookies["SelectedDBInfo"] != null)
            {
                Response.Cookies.Remove("SelectedDBInfo");
            }

            //根据用户行为还原检索状态
            ViewBag.SearchLogID = searchLog;
            if (-1 != searchLog)
            {
                IList<SearchQuery> searchQueryList = new List<SearchQuery>();
                string order;
                string dbid;
                string classCode;
                centerService.GetMultiSearchLogDetail(searchLog, searchQueryList, out order, out classCode, out dbid);
                if (searchQueryList != null && searchQueryList.Count > 0)
                {
                    searchField = searchQueryList[0].Text;
                    conditionKey = searchQueryList[0].Key;
                    conditionType = searchQueryList[0].ConditionType;
                }
                ViewBag.SearchQuery = searchQueryList;
                checkDatabaseID = dbid;
                unionDBClassID = classCode;
                if (!string.IsNullOrEmpty(order))
                {
                    string sortField = order.Substring(0, order.LastIndexOf(' '));
                    string sortType = order.Substring(order.LastIndexOf(' ') + 1);
                    ViewBag.SortFiledNow = sortField;
                    ViewBag.SortDescAsc = sortType;
                }
            }

            IList<SYS_CMS_TOPIC> topicInfo = topicService.GetTopicInfo(topicCode);
            if (topicInfo != null && topicInfo.Count > 0)
            {
                ViewBag.TitlePic = topicInfo[0].TopicPic;
                ViewBag.TitleTopic = topicInfo[0].TopicName;
                ViewBag.CopyRight = topicInfo[0].CopyRight;
                ViewBag.Layout = "~/Views/Shared/_LayoutTopic" + topicInfo[0].TopicPage + ".cshtml";
            }
            ViewBag.DateStr = System.DateTime.Now.ToString("yyyy-MM-dd") + "  " + System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat.GetDayName(DateTime.Now.DayOfWeek); ;
            ViewBag.TopicCode = topicCode;

            ViewBag.SearchField = searchField;
            ViewBag.ConditionKey = conditionKey;
            ViewBag.ConditionType = conditionType;
            ViewBag.SelectedDataBase = checkDatabaseID;
            ViewBag.UnionDBClassID = unionDBClassID;
            IList<DBCLASS> classList = searchService.GetUnionClass();
            ViewBag.UnionDBClassInfo = classList;
            if (string.IsNullOrEmpty(unionDBClassID) && classList != null && classList.Count > 0)
            {
                unionDBClassID = classList[0].ClassCode;
            }
            ViewBag.SeachDataBase = searchService.GetUnionDBList(unionDBClassID);//所有数据库

            ViewBag.SeachInfo = searchService.GetUnionFieldList(FieldType.Search);//检索字段
            return View();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="form"></param>
        /// <returns></returns>
        [HttpPost]
        [ValidateInput(false)]
        [SecurityActionFilter]
        public ActionResult Search()
        {
            int pageSize = 10;//每页显示记录数
            int pageIndexNow = 1;// 当前页    
            //string strOrder = "";
            ViewBag.listAbstract = "absc";//列表显示模式
            if (Request.Params["listOrabst"] != null && Request.Params["listOrabst"].ToString() != "")
            {
                ViewBag.listAbstract = Request.Params["listOrabst"];
            }
            IList<SearchQuery> searchQuery = new List<SearchQuery>();
            string checkDatabaseID = Request.Params["checkDatabaseID"];
            int currentSubid = int.Parse(Request.Params["currentSubid"]);
            string classCode = Request.Params["classCode"];

            pageIndexNow = int.Parse(Request["pageIndexNow"]);
            //string conditionValue = string.IsNullOrEmpty(Request["beforeConditionValue"]) ? "" : "*" + Request["beforeConditionValue"];
            string conditionValue = string.IsNullOrEmpty(Request["beforeConditionValue"]) ? "" : Request["beforeConditionValue"];
            int Querystr = string.IsNullOrEmpty(Request["beforeQueryValue"]) ? 0 :int.Parse(Request["beforeQueryValue"].ToString());
            string beforeconkey = string.IsNullOrEmpty(Request["beforeConditionKey"]) ? "" : Request["beforeConditionKey"];
            if (beforeconkey != "")
            {
                searchQuery.Add(new SearchQuery(beforeconkey, conditionValue, (ConditionType)Querystr));
            }
            string contype = "";
            string conkey = "";
            for (int i = 1; i <= currentSubid; i++)
            {
                //conditionValue = string.IsNullOrEmpty(Request["beforeConditionValue" + i]) ? "" : "*" + Request["beforeConditionValue" + i];
                 Querystr = string.IsNullOrEmpty(Request["beforeQueryValue" + i]) ? 0 : int.Parse(Request["beforeQueryValue" + i].ToString());//模糊精确
                 conditionValue = string.IsNullOrEmpty(Request["beforeConditionValue" + i]) ? "" : Request["beforeConditionValue" + i];//值
                 contype = string.IsNullOrEmpty(Request["beforeConditionType" + i]) ? "0" : Request["beforeConditionType" + i];//and or
                 conkey = string.IsNullOrEmpty(Request["beforeConditionKey" + i]) ? "" : Request["beforeConditionKey" + i];//关键词
                 if (conkey != "") //如果查询字段为空则该条件不成立
                 {
                     searchQuery.Add(new SearchQuery(conkey, conditionValue, (ConditionType)Querystr, (SearchMatchType)int.Parse(contype)));
                 }
            }
            //strOrder = GetSort();
            SetDataResult(checkDatabaseID, searchQuery, pageIndexNow, pageSize, classCode);//检索
            if (!String.IsNullOrEmpty(Request.Params["TopicCode"]))
            {
                ViewBag.TopicCode = Request.Params["TopicCode"];
            }

            return PartialView("ResultList");
        }
        /// <summary>
        /// 读取数据，分页
        /// </summary>
        /// <param name="checkDatabaseID"></param>
        /// <param name="searchQuery"></param>
        /// <param name="pageIndexNow"></param>
        /// <param name="pageSize"></param>
        private void SetDataResult(string checkDatabaseID, IList<SearchQuery> searchQuery, int pageIndexNow, int pageSize, string classCode)
        {

            int sumCount = 0;//总条数
            int sumPage = 0;//一共多少页
            int disPgae = 8;  //默认显示页数，当页数大于该数值时，按规定格式显示
            string strOrder = "";
            strOrder = GetSort();
            string query = "";
            DataSet ds = searchService.MultiSearch(checkDatabaseID, "", searchQuery, 0, "", "", strOrder, pageIndexNow, pageSize, classCode, out query);
            if (!string.IsNullOrEmpty(query))
            {
                LogOpr.Search(checkDatabaseID, "", query, strOrder, "MultiSearch", classCode, "", "");
            }
            if (ds.Tables.Count > 0 && ds.Tables["infos"] != null)
            {
                ViewBag.SearchResult = ds.Tables[0];
                int len = ds.Tables["infos"].Rows.Count;
                if (len > 0)
                {
                    for (int i = 0; i < len; i++)
                    {
                        sumCount += int.Parse(ds.Tables["infos"].Rows[i]["count"].ToString());//总条数
                    }
                }
                sumPage = sumCount / pageSize; //一共多少页
                if (sumCount % pageSize != 0)
                {
                    sumPage = sumPage + 1;
                }
                ViewBag.TotalPage = sumPage;
                ColumnAliasHelper objhelp = new ColumnAliasHelper();
                ViewBag.PageList = objhelp.GetPageList(pageIndexNow, sumPage, disPgae);
                ViewBag.PageNow = pageIndexNow;//当前页
                ViewBag.PageSize = pageSize;
                ViewBag.ResultCount = sumCount.ToString("N0");
                ViewBag.ResultColumnInfo = ds.Tables["infos"];
                ViewBag.DisplayColumnInfo = ds.Tables["ColumnInfo"];
                //Session["ResultColumnInfo"] = ds.Tables["infos"];
                HttpCookie cookie = new HttpCookie("ResultColumnInfo");
                cookie.Value = SerializeHelper.BinarySerialize(ds.Tables["infos"]);
                Response.Cookies.Add(cookie);
            }
        }

        /// <summary>
        /// 左侧数据库列表
        /// </summary>
        /// <param name="form"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult GetDateBaseList()
        {
            string info = Request.Cookies["ResultColumnInfo"].Value;
            ViewBag.ResultColumnInfo = SerializeHelper.BinaryDeSerialize<DataTable>(info);
            Response.Cookies.Remove("ResultColumnInfo");
            //ViewBag.ResultColumnInfo = Session["ResultColumnInfo"];
            return PartialView("DataBaseList");
        }

        /// <summary>
        /// 页面排序
        /// </summary>
        /// <param name="dbID"></param>
        /// <returns></returns>
        private string GetSort()
        {
            string strOrder = "";
            IList<DBUSFIELD> listSort = searchService.GetUnionFieldList(FieldType.Sort);//排序字段
            if (listSort != null && listSort.Count > 0) //初始化
            {
                ViewBag.SortField = listSort;
                ViewBag.SortFiledNow = listSort[0].RealFieldName;//当前排序字段
                ViewBag.SortDescAsc = "desc";//默认按降序
                strOrder = listSort[0].RealFieldName + " desc";

            }
            else
            {
                ViewBag.SortField = null;
                ViewBag.SortFiledNow = "";//
                ViewBag.SortDescAsc = "";
            }
            if (Request["sortField"] != null && Request["sortField"].ToString() != "")//如果页面有值就重新赋值
            {
                ViewBag.SortFiledNow = Request["sortField"];
                if (Request["sortDescAsc"] != "")
                {
                    ViewBag.SortDescAsc = Request["sortDescAsc"];
                }
                strOrder = Request["sortField"] + " " + Request["sortDescAsc"];
            }
            return strOrder;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="unionDBClassID"></param>
        /// <returns></returns>
        public ActionResult GetDBClass(string targetClassID, string preClassID, string checkDBID,string type)
        {
            //获得SelectedDBInfo

            //保存当前分类的选择DB状态

            //根据分类获得对应的数据库列表
            IList<DBCONFIG> dbList = searchService.GetUnionDBList(targetClassID);
            ViewBag.SeachDataBase = searchService.GetUnionDBList(targetClassID);
            //获得新分类的数据库选择状态
            if (checkDBID == "-1")
            {
                ViewBag.SelectedDataBase = string.Join(",", dbList.Where(c => c.DefaultSelected == 1).Select(c => c.DbID));
            }
            else
            {
                ViewBag.SelectedDataBase = checkDBID;
            }
            ViewBag.Type = type;
            //System.Threading.Thread.Sleep(10000);
            return PartialView("UnionClassDBList");
        }
    }
}
